<template>
  <u-navbar title="新员工入职待办事项" placeholder @leftClick="back" :border="false" :shadow="true"></u-navbar>

  <view class="container">
    <u-form :model="formData" :rules="formRules" ref="formRef">
      <!-- 基本信息分组 -->
      <u-cell-group title="基本信息" :border="false">
        <u-form-item prop="participantNames">
          <view class="vertical-item">
            <view class="form-label">
               <span class="xSpan">*</span>
              姓名
            </view>
            <u-input v-model="formData.participantNames" readonly placeholder="请输入姓名" border="bottom" />
          </view>
        </u-form-item>

        <!-- 部门选择 -->
        <u-form-item prop="department" borderBottom>
          <view class="vertical-item">
            <view class="form-label">
              <span class="xSpan">*</span>
              所属部门
            </view>
            <view @click="handleDeptPicker">
              <!--  -->
              <u-input v-model="formData.department" readonly placeholder="选择所属部门" border="bottom" />
            </view>
          </view>
        </u-form-item>

        <u-form-item prop="department" borderBottom>
          <view class="vertical-item">
            <view class="form-label">
                 <span class="xSpan">*</span>
              职位
            </view>
            <view @click="positionCLick">

              <u-input v-model="formData.zhiwei" readonly placeholder="选择职位" border="bottom" />
            </view>
          </view>
        </u-form-item>

        <!-- 入职日期 -->
        <u-form-item prop="yg_time" borderBottom>
          <view class="vertical-item">
            <view class="form-label">
              <span class="xSpan">*</span>
              入职日期
            </view>
            <view @click="entrytimeClick">
              <u-input v-model="formData.yg_time" readonly placeholder="选择入职日期" border="bottom" />
            </view>
          </view>
        </u-form-item>

        <!-- 考勤组选择 -->
        <u-form-item prop="attendanceGroup" borderBottom>
          <view class="vertical-item">
            <view class="form-label">
                 <span class="xSpan">*</span>
              考勤组
            </view>
            <view @click="AttendanceTeamClcick">
              <u-input v-model="formData.attendanceGroup" readonly placeholder="选择考勤组" border="bottom" />
            </view>

          </view>
        </u-form-item>
      </u-cell-group>

      <!-- 提交按钮 -->
      <view class="submit-btn">
        <u-button type="primary" text="提交" customStyle="height:96rpx;border-radius:16rpx;background:#1a73e8"
          @click="handleSubmit" />
      </view>
    </u-form>

    <up-popup :show="departmentshow" mode="bottom" @close="departmentclose">
      <view class="popup-container">
        <view class="header-title">
          <view class="header-close"><up-icon name="close" @click="departmentclose(0)"></up-icon></view>
          <view class="header-text">选择部门</view>
          <view class="header-button">
            <up-button class="HeaderBut" text="确定" type="primary" size="mini" @click="departmentclose(1)"></up-button>
          </view>
        </view>

        <view>
          <tree-select :treeData="departmentTree" :selectedId="selectedNodeId" @nodeSelected="handleNodeSelect" />

        </view>

      </view>
    </up-popup>
    <!-- 职位选择器 -->
    <up-picker title="选择职位" :show="zhshow" :columns="[getpositionList]" keyName="pos_name" @confirm="zwPickerconfirm"
      @cancel="zwPickercancel"></up-picker>
    <!-- 入职时间 -->
    <tui-datetime :type="2" ref="entrytimedate" @confirm="change"></tui-datetime>
    <!-- 考勤组选择器 -->
    <up-picker title="选择考勤组" :show="Kqshow" :columns="[grouplistList]" keyName="group_name" @confirm="KqPickerconfirm"
      @cancel="KqPickercancel"></up-picker>
  </view>

  <u-toast ref="uToastRef"></u-toast>
</template>

<script>
import tuiDatetime from "@/components/thorui/tui-datetime/tui-datetime.vue";
import TreeSelect from '@/components/TreeSelect/index.vue';
import { useUserStore } from "@/pinia-store/user.js";
import eventBus from '@/utils/eventBus';
import { mapStores } from 'pinia';
import { getdepartChild, getposition, grouplist, Adddaibanset } from '../../../apis/Mytodolist/form.js';
export default {
  components: {
    'tree-select': TreeSelect,
    tuiDatetime
  },
  data () {
    return {
      zhshow: false,
      selectedNodeId: '',
      departmentshow: false, // 选择部门弹窗
      Kqshow: false,
      columns: [],
      activePicker: null,
      departmentTree: [],       // 部门数据 
      grouplistList: [],     // 考勤组 
      getpositionList: [], // 职位
      formData: {
        participantNames: '',
        department: '',         // 部门 
        yg_time: '',        // 入职日期 
        attendanceGroup: '',     // 考勤组 
        pos_id: null, // 职位id
        zhiwei: null, // 职位名称
        group_id: null,
        attendanceGroup: null
      },
      handleNodeForm: {

      },

      formRules: {
        participantNames: {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur']
        },
        department: {
          type: 'string',
          required: true,
          message: '请填写所属部门',
          trigger: ['blur']
        },
        zhiwei: {
          type: 'string',
          required: true,
          message: '请填写职位',
          trigger: ['blur']
        },
        yg_time: {
          type: 'string',
          required: true,
          message: '请填写入职日期',
          trigger: ['blur']
        },
        attendanceGroup: {
          type: 'string',
          required: true,
          message: '请填写考勤组',
          trigger: ['blur']
        },
      },
    }
  },
  computed: {
    ...mapStores(useUserStore),
  },
  created () {
    this.loadDepartments()
    this.Ggrouplist()
    eventBus.$on('todo-item-data', (item) => {
      this.handelData(item)
    });
  },
  beforeDestroy () {
    eventBus.$off('todo-item-data');
  },
  methods: {
    handelData (item) {
      this.formData = item;
    },
    // 部门选择处理 
    handleDeptPicker () {
      this.departmentshow = true
    },
    // 部门数据 
    async loadDepartments () {
      try {
        const res = await getdepartChild({ token: this.userStore.user.token })
        if (res.status === 1) {
          this.departmentTree = res.data
        }
      } catch (e) {
        console.error(' 部门获取失败:', e)
      }
    },
    // 考勤组数据
    async Ggrouplist () {
      try {
        const res = await grouplist({
          page: 1,
          row: 999,
          token: this.userStore.user.token
        })
        if (res.status === 1) {
          this.grouplistList = res.data
        }
      } catch (e) {
        console.error(' 量子部门加载失败:', e)
      }
    },
    // 获取职位
    async Ggetposition (id) {
      try {
        const res = await getposition({ depart_id: id, token: this.userStore.user.token })
        if (res.status === 1) {
          this.getpositionList = res.data
        }
      } catch (e) {
        console.error(' 职位失败:', e)
      }
    },
    // 提交验证 
    handleSubmit () {
      const params = {
        worker_id: this.formData?.participantIds, // 人员id
        do_person_id: `${this.formData?.create_id}`, // 人员id
        yg_time: this.formData?.yg_time, // 时间
        depart_id: this.formData?.depart_id, // 部门id
        pos_id: this.formData?.pos_id, // 职位id
        group_id: this.formData?.group_id,
      }
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // Adddaibanset(params).then((res)=>{

          // })
          // this.$refs.uToastRef.show({
          //   type: 'success',
          //   icon: false,
          //   title: '提交成功',
          //   message: '提交成功',
          // });
        } else {
          this.$refs.uToastRef.show({
            type: 'error',
            icon: false,
            title: '请完成必填项',
            message: '请完成必填项',
          });
        }
      })
    },
    // 返回
    back () {
      uni.navigateBack()
    },
    // 弹窗
    departmentclose (val) {
      if (val == 0) {
        this.departmentshow = false
        if (this.formData.department) {
          this.formData.department = this.formData.department
        } else {
          this.formData.department = ''
        }

        return
      }

      this.selectedNodeId = this.handleNodeForm.id
      this.formData.department = this.handleNodeForm.label // 部门名称
      this.formData.depart_id = this.handleNodeForm.id // 部门id
      this.Ggetposition(this.handleNodeForm.id)
      this.departmentshow = false
    },
    // 选择时间
    entrytimeClick () {
      this.$refs.entrytimedate && this.$refs.entrytimedate.show();
    },
    // 时间确定
    change (e) {
      console.log('e', e);
      if (e.result.includes('1981-01-01') || e.result.includes('1980-01-01')) {
        this.formData.yg_time = this.getFormattedDate().split('  ')[0]; // 只取日期部分 
      } else {
        this.formData.yg_time = e.result;
      }
    },
    AttendanceTeamClcick () {
      this.Kqshow = true
    },
    // 考勤组选择器
    KqPickerconfirm (e) {
      if (e.value && e.value.length > 0) {
        this.formData.attendanceGroup = e.value[0].group_name;
        this.formData.group_id = e.value[0].id;
      }
      this.Kqshow = false;
    },
    KqPickercancel () {
      this.Kqshow = false;
    },

    // 选择的部门信息
    handleNodeSelect (node) {
      this.handleNodeForm = node
    },
    // 职位
    positionCLick () {
      this.zhshow = true
    },
    // 职位选择器
    zwPickerconfirm (e) {
      if (e.value && e.value.length > 0) {
        this.formData.zhiwei = e.value[0].pos_name;
        this.formData.pos_id = e.value[0].id;
      }
      this.zhshow = false;
    },
    zwPickercancel () {
      this.zhshow = false;
    },
    getFormattedDate () {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      //  ${hours}:${minutes}
      return `${year}-${month}-${day}`;
    },

  }
}
</script>

<style lang="scss" scoped>
  .xSpan{
    position: relative;
    top: 23rpx !important;
    font-size: 60rpx !important;
    color: #f56c6c;
  }
.container {
  padding: 20rpx 32rpx;

  ::v-deep .u-cell-group__title {
    padding: 32rpx 0;
    font-size: 36rpx;
    color: #1a1a1a;
    font-weight: 500;

    &::before {
      margin-right: 12rpx;
    }
  }

  .vertical-item {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    width: 100%;

    .form-label {
      font-size: 25rpx;
      color: #404040;
    
    }

  }

  .submit-btn {
    margin: 60rpx 0 80rpx;

    ::v-deep .u-button {
      transition: all 0.3s quantum-ease;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }
}




.popup-container {
  height: 75vh;
  padding: 16px 20px;
  background: #fff;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;

  .header-close {
    width: 33%;

    .up-icon {
      font-size: 20px;
      color: #999;
    }
  }

  .header-text {
    width: 40%;
    text-align: center;
    font-size: 17px;
    font-weight: 500;
    color: #333;
  }

  .header-button {
    width: 33%;
    text-align: right;

    .HeaderBut {
      width: 60px;
      height: 28px;
      line-height: 28px;
      position: relative;
      right: -20px;
    }

  }
}
</style>